-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
--
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
local cjson = require 'cjson'
local performance_collection = {}

local function get_thermal_fans(list)
    local res = {}
    for _, path in pairs(list) do
        local ok, fan_obj = pcall(mdb.get_object, bus, path, 'bmc.kepler.Systems.Fan')
        if not ok then
            goto continue
        end
        res[#res + 1] = fan_obj

        ::continue::
    end
    return res
end

function performance_collection.get_fans_info(fan_path_list)
    local fan_info_table = {}
    local max_fan_id = 0
    local cjson_rsp = cjson.json_object_new_array()
    local thermal_fans = get_thermal_fans(fan_path_list)
    -- 所有风扇按照对称风扇进行id插入排序
    for _, fan_obj in pairs(thermal_fans) do
        if fan_obj.IsTwins == true then
            fan_info_table[fan_obj.FanId * 2 - 1] = fan_obj.FrontSpeed * fan_obj.Coefficient
            fan_info_table[fan_obj.FanId * 2] = fan_obj.RearSpeed * fan_obj.Coefficient
        else
            fan_info_table[fan_obj.FanId * 2] = fan_obj.RearSpeed * fan_obj.Coefficient
        end
        max_fan_id = fan_obj.FanId > max_fan_id and fan_obj.FanId or max_fan_id
    end
    local cjson_rsp_size = 0
    for index = 1, max_fan_id * 2, 1 do
        if fan_info_table[index] then
            cjson_rsp_size = cjson_rsp_size + 1
            cjson_rsp[cjson_rsp_size] = cjson.json_object_new_object()
            cjson_rsp[cjson_rsp_size]["@odata.id"] = "/redfish/v1/Chassis/1/Thermal#/Fans/" .. cjson_rsp_size - 1
            cjson_rsp[cjson_rsp_size]["Reading"] = fan_info_table[index]
        end
    end
    return cjson_rsp
end

return performance_collection
